package de.idgard.android.proxy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;

public class IDGardProxyRead extends Thread {
	private final int BUFFER_SIZE = 65535;
	private BufferedInputStream in;
	private BufferedOutputStream out;
	private IDGardProxyHTTPSession connection;
	private IDGardProxyServer server;

	public IDGardProxyRead(IDGardProxyServer server,
			IDGardProxyHTTPSession connection, BufferedInputStream l_in,
			BufferedOutputStream l_out) {
		in = l_in;
		out = l_out;
		this.connection = connection;
		this.server = server;
		setPriority(Thread.MAX_PRIORITY);
		start();
	}

	public void run() {
		read();

		server = null;
		connection = null;
		in = null;
		out = null;

	}

	private void read() {
		int bytes_read = 0;
		byte[] buf = new byte[BUFFER_SIZE];
		try {
			while (true) {
				bytes_read = in.read(buf);
				if (bytes_read != -1) {
					out.write(buf, 0, bytes_read);
					out.flush();
					server.addBytesRead(bytes_read);
				} else
					break;
			}
		} catch (IOException e) {
		}

		try {
			if (connection.getStatus() != connection.SC_CONNECTING_TO_HOST)
				connection.getLocalSocket().close();
		} catch (IOException e_socket_close) {
			e_socket_close.printStackTrace();
		}

		buf = null;
	}

	/**
	 * stop the thread by closing the socket
	 */
	public void close() {
		try {
			in.close();
		} catch (Exception e) {
		}
	}
}
